<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcel"
          >导出</el-button>
          <!-- 这里的混入是从全局引入，直接使用的 -->
          <!-- <el-button :disabled="!checkPermission('addEmployees')" size="small" type="primary" @click="showDialog=true">新增员工</el-button> -->
          <!-- 使用v-if直接消失隐藏，可以避免被人前端攻入修改 -->
          <el-button v-if="checkPermission('addEmployees')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="头像" width="200">
            <template #default="{row}">
              <img
                v-imgerr="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                class="avatar"
                @click="showQRCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="correctionTime" sortable="">
            <template #default="{ row }">
              <!-- 过滤时间 -->
              {{ row.correctionTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template #default="{ row }">
              <!-- value这里接收的true或者false -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>

      <el-dialog title="二维码" :visible="isShowQRCode" @close="isShowQRCode=false">
        <el-row type="flex" justify="center">

          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <AssignRole ref="assignRole" :user-id="userId" :show-dialog.sync="showRoleDialog" />

      <add-employees :show-dialog.sync="showDialog" @addEmployee="getEmployeesInfoList" />
    </div>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools'
import { getEmployeesInfoList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import AddEmployees from './components/add-employees.vue'
// 安装第三方库二维码
import QRCode from 'qrcode'

import AssignRole from './components/assign-role.vue'

// 默认导入
//  每次进来都进行导入, 如果用的频率不高, 就有点浪费
// import { export_json_to_excel } from '@/vendor/Export2Excel'
export default {
  // 过滤时间
  // filters: {
  //   formatDate(val) {
  //     return val.slice(0, 7)
  //   }
  // },
  // components: {
  //   PageTools
  // }
  components: {
    AddEmployees,
    AssignRole
  },
  data() {
    return {
      showDialog: false,
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      list: [],
      // 控制显示二维码
      isShowQRCode: false,
      // 角色权限的弹窗
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeesInfoList()
  },
  methods: {
    async getEmployeesInfoList() {
      const { rows, total } = await getEmployeesInfoList(this.page)
      // 本地数据服务器缺失 了enableState属性，这里对所遇到额员工进行处理，如果没有这个值补1
      this.list = rows.map((item) => ({
        ...item,
        enableState: item.enableState || 1
      }))
      this.page.total = total
    },
    currentChange(newPage) {
      console.log(newPage)
      this.page.page = newPage
      this.getEmployeesInfoList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // console.log(cellValue)
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '不详'
    },
    // 导出
    async exportExcel() {
      // 1、获取所有的数据
      const { rows } = await getEmployeesInfoList({
        page: 1,
        size: this.page.total
      })
      // console.log(rows)

      // 进行数据转换
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 安装字典顺序生成表头
      const header = Object.keys(dict)
      // 再点击后触发函数时按需导入
      // import函数是一个promise会将所有导入文件里面暴露的变量都放在res对象中
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')

      // 将用户数组里面包裹的对象，都变成数组，因为导出excel的要求
      // 导出的具体数据
      const data = rows.map((item) => {
        // console.log('1', item)
        return this.obj2arr(item, dict)
      })

      export_json_to_excel({
        header,
        data,
        filename: '员工数据表'
      })
    },
    // 将对象转换为数组且key转为中文的方法
    obj2arr(user, dict) {
      const newUser = []
      // 中间这里写对象转数组逻辑
      // 因为表头是根据字典顺序生成的，所以用户数组的熟悉也要一样
      // 遍历字典，就用当前的英文key取值，放入数组当中
      for (const key in dict) {
        const enKey = dict[key] // 获得英文
        const value = user[enKey] // 获得值
        // 判断下聘用格式，导出时转换格式

        if (enKey === 'formOfEmployment') {
          const obj = EmployeeEnum.hireType.find((item) => item.id === value)
          newUser.push(obj ? obj.value : '未知')
          // 判断下时间格式，导出时转换下
        } else if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          newUser.push(formatDate(value))
        } else {
          // 其他的就直接导出
          newUser.push(value)
        }
      }
      // console.log(newUser)
      return newUser
    },
    // 删除员工
    async delEmployee(id) {
      // 1、弹出提示
      await this.$confirm('您确定删除吗？')
      // 2、调用接口
      await delEmployee(id)
      // 3、弹出成功
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      // 4、更新页面
      this.getEmployeesInfoList()
    },
    // 弹出二维码
    showQRCode(imgUrl) {
      console.log(imgUrl)
      if (imgUrl) {
        this.isShowQRCode = true
        this.$nextTick(() => {
          // 等弹窗渲染完，创建二维码
          // 三个参数
          // 1、canvas dom
          // 2、字符串
          // 3、可选配置对象
          QRCode.toCanvas(this.$refs.myCanvas, imgUrl, {
            width: 300,
            color: {
              dark: '#43731e'
            }
          })
        })
      }
    },
    // 角色权限弹窗打开
    async assignRole(id) {
      this.userId = id
      // 回显原有的角色权限数据
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
    // 判断能否执行新增操作权限
    // checkPermission(btnName) {
    //   const roles = this.$store.state.user.userInfo.roles
    //   // 判断不存在就返回true
    //   return roles && roles.points.indexOf(btnName) !== -1
    // }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 200px;
  height: 140px;
  object-fit: cover;
}
</style>
